package com.ea.eadp.nexus.proxy.tests.tracking;

import static org.testng.Assert.assertEquals;

import java.util.HashMap;

import org.testng.annotations.Test;

import com.ea.eadp.nexus.test.common.AccessToken;
import com.ea.eadp.nexus.test.common.NexusGatewayApiEnum;
import com.ea.eadp.nexus.test.common.TestUtil;
import com.ea.eadp.nexus.test.common.ApiClients.NexusConnectApi;
import com.ea.eadp.nexus.test.common.ApiClients.NexusGatewayApi;
import com.ea.eadp.nexus.test.common.ApiClients.NucleusApi;
import com.ea.eadp.rest.tracking.generated.identity.UserLogEntriesType;
import com.ea.eadp.test.shared.utility.RandomFactory;
import com.ea.nucleus.caseproperties.CaseProperties;
import com.ea.nucleus.caseproperties.Priority;
import com.ea.nucleus.caseproperties.Release;
import com.ea.nucleus.caseproperties.Status;
import com.ea.nucleus.caseproperties.ReleaseFeatures.Apr2015;
import com.ea.nucleus.eaid.pid.jaxb.AuthMethodType;
import com.ea.nucleus.eaid.pid.jaxb.AuthRequestIdentificationType;
import com.ea.nucleus.eaid.user.User.EmailStatus;
import com.ea.nucleus.eaidpid.integration.client.orchestratedauthentication.PostAuthenticationByEmailAddressRequest;
import com.ea.nucleus.eaidpid.integration.client.orchestratedauthentication.PostAuthenticationByEmailAddressService;
import com.ea.nucleus.eaidpid.integration.client.pids.PutPidRequest;
import com.ea.nucleus.eaidpid.integration.client.pids.PutPidService;

@CaseProperties(
        release = Release.Apr2015,
        status = Status.Enable,
        owner = "Marvin"
)
public class QueryUserActivitiy {
    private static final String CLIENT_ID = "wwce-sovereign";
    private static final String CLIENT_SECRET = "wwce_secret";

    @CaseProperties(
            status = Status.Enable,
            priority = Priority.Dailies,
            features = Apr2015.GOPFR_854,
            description = "query user login",
            steps = {
                    "1. Create a user",
                    "2. Log in",
                    "3. Query the user's login history through nexus proxy",
                    "3.1 Verify that the user login could get fetched correctly"
            }
    )
    @Test(groups="GOPFR-854", timeOut=60000)
    public void queryLoginHistory() throws Exception {
        String email = RandomFactory.getRandomEmailAddress();
        String password = "Passw0rd!";
        String pidType = TestUtil.getPidID(NucleusApi.instance().postPid(email, password)).toString();

        PostAuthenticationByEmailAddressRequest request = new PostAuthenticationByEmailAddressRequest();

        // little essential set up...
        request.addHeader("X-Source", "eadm");
        String ip = RandomFactory.getRandomIp().replaceAll("\\d+\\.", "10.");
        request.getRequestData().setIpAddress(ip);
        request.getRequestData().setAllowAnonymousPid("true");
        request.getRequestData().setAllowUnderagePid("true");

        request.getRequestData().setMethod(new AuthMethodType());
        request.getRequestData().getMethod().setType("PASSWORD");
        request.getRequestData().getMethod().setValue(password);
        request.getRequestData().setIdentification(new AuthRequestIdentificationType());
        request.getRequestData().getIdentification().setEmailAddress(email);

        PostAuthenticationByEmailAddressService.instance().post(request);

        AccessToken token = NexusConnectApi.instance().getTokenWithClientSecretAndRedirectUri("client_credentials", null, pidType, null, null, CLIENT_ID, CLIENT_SECRET, null, false, null);
        HashMap<String,String> context = new HashMap<String,String>();
        context.put("pid", pidType);

        UserLogEntriesType response = null;

        for (int i = 0; i < 30; i++) {
            response = TestUtil.parseJson(NexusGatewayApi.instance().get(token, NexusGatewayApiEnum.get_user_login_history, context), UserLogEntriesType.class, "userLogEntries");

            if (!response.getUserLogEntry().isEmpty()) {
                break;
            }

            Thread.sleep(1000L);
        }

        assertEquals(response.getUserLogEntry().size(), 1, "user login history is not available when queried from nexus proxy");
    }

    @CaseProperties(
            status = Status.Enable,
            priority = Priority.Dailies,
            features = Apr2015.GOPFR_855,
            description = "query user account change",
            steps = {
                    "1. Create a user",
                    "2. Verify its email",
                    "3. Query the user's account change history through nexus proxy",
                    "3.1 Verify that the user account change could get fetched correctly"
            }
    )
    @Test(groups="GOPFR-855", timeOut=60000)
    public void queryAccountChangeHistory() throws Exception {
        String email = RandomFactory.getRandomEmailAddress();
        String password = "Passw0rd!";
        String pidType = TestUtil.getPidID(NucleusApi.instance().postPid(email, password)).toString();

        PutPidRequest request = new PutPidRequest(pidType);
        request.getRequestData().setEmailStatus(EmailStatus.VERIFIED.name());
        PutPidService.instance().put(request);
        
        AccessToken token = NexusConnectApi.instance().getTokenWithClientSecretAndRedirectUri("client_credentials", null, pidType, null, null, CLIENT_ID, CLIENT_SECRET, null, false, null);
        HashMap<String,String> context = new HashMap<String,String>();
        context.put("pid", pidType);
        
        UserLogEntriesType response = null;

        for (int i = 0; i < 30; i++) {
            response = TestUtil.parseJson(NexusGatewayApi.instance().get(token, NexusGatewayApiEnum.get_user_account_change_history, context), UserLogEntriesType.class, "userLogEntries");

            if (!response.getUserLogEntry().isEmpty()) {
                break;
            }

            Thread.sleep(1000L);
        }

        assertEquals(response.getUserLogEntry().size(), 1, "user account change history is not available when queried from nexus proxy");
    }
}
